package cn.zhku.news.web.servlet.admin;

import cn.itcast.commons.CommonUtils;
import cn.zhku.news.domain.News;
import cn.zhku.news.service.NewsService;

import java.awt.Image;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.ImageIcon;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class AdminNewsAddServlet
 */
@WebServlet("/AdminNewsAddServlet")
public class AdminNewsAddServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	NewsService newsService = new NewsService();
    AdminNewsServlet AdminNewsServlet = new AdminNewsServlet();

    public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		/*
		 * 1. 把表单数据封装到Book对象中
		 *   * 上传三步
		 */
		// 创建工厂
		DiskFileItemFactory factory = new DiskFileItemFactory(15 * 1024, new File("F:/f/temp"));
		// 得到解析器
		
		ServletFileUpload sfu = new ServletFileUpload(factory);
		// 设置单个文件大小为15KB
		sfu.setFileSizeMax(100000 * 1024);
		// 使用解析器去解析request对象，得到List<FileItem>
		try {
			List<FileItem> fileItemList = sfu.parseRequest(request);
			/*
			 * * 把fileItemList中的数据封装到News对象中
			 *   > 把所有的普通表单字段数据先封装到Map中
			 *   > 再把map中的数据封装到News对象中
			 */
			Map<String,String> map = new HashMap<String,String>();
			for(FileItem fileItem : fileItemList) {
				if(fileItem.isFormField()) {
					map.put(fileItem.getFieldName(), fileItem.getString("UTF-8"));
				}
			}

			News news = CommonUtils.toBean(map, News.class);
			System.out.println(news);
			// 为book指定bid
			//news.setNewsid(CommonUtils.uuid());
			/*
			 * 需要把Map中的aid封装到Category对象中，再把Category赋给Book
			 */
			
			/*
			 * 2. 保存上传的文件
			 *   * 保存的目录
			 *   * 保存的文件名称
			 */
			// 得到保存的目录
			String imgSavepath = this.getServletContext().getRealPath("/news/img");
			String textSavepath = this.getServletContext().getRealPath("/news/text");
			// 得到文件名称：给原来文件名称添加uuid前缀！避免文件名冲突
			
			String imgFileName = fileItemList.get(2).getName();
			String textFileName = fileItemList.get(1).getName();
			
			String NewImgFileName = CommonUtils.uuid()+imgFileName.substring(imgFileName.lastIndexOf("."));
			String NewTextFileName = CommonUtils.uuid()+imgFileName.substring(textFileName.lastIndexOf("."));
			
			
			/*
			 * 校验文件的扩展名
			 */
			if(!NewImgFileName.toLowerCase().endsWith("jpg")) {
				request.setAttribute("msg", "您上传的图片不是JPG扩展名！");
				request.getRequestDispatcher("/news/add.jsp")
						.forward(request, response);
				return;
			}
			if(!NewTextFileName.toLowerCase().endsWith("txt")) {
				request.setAttribute("msg", "您上传的文档不是txt扩展名！");
				request.getRequestDispatcher("/news/add.jsp")
						.forward(request, response);
				return;
			}
			
			
			// 使用目录和文件名称创建目标文件
			File imgFile = new File(imgSavepath, NewImgFileName);
			File textFile = new File(textSavepath, NewTextFileName);
			// 保存上传文件到目标文件位置
			System.out.println(imgFile+"  "+textFile);
			fileItemList.get(2).write(imgFile);
			fileItemList.get(1).write(textFile);
			
			/*
			 * 3. 设置News对象的image，即把图片的路径设置给Book的image
			 */
			news.setContent("/news/content" + NewTextFileName);
			news.setImage("/news/img" + NewImgFileName);
			
			//填充新闻的nid和管理员的aid;
			news.setNid(CommonUtils.uuid());
			news.setAid(CommonUtils.uuid());
			news.setDate(new Date());
			
			
			/*
			 * 4. 使用NewsService完成保存
			 */
			newsService.add(news);
			
			
			/*
			 * 校验图片的尺寸
			 */
			Image image = new ImageIcon(imgFile.getAbsolutePath()).getImage();
			if(image.getWidth(null) > 10000 || image.getHeight(null) > 10000) {
				imgFile.delete();//删除这个文件！
				request.setAttribute("msg", "您上传的图片尺寸超出了10000* 10000！");
				
				request.getRequestDispatcher("/news/add.jsp")
						.forward(request, response);
				return;
			}
			
			
			/*
			 * 5. 返回到新闻上传列表列表
			 */
			AdminNewsServlet.query(request, response);
			request.getRequestDispatcher("/news/list.jsp")
			.forward(request, response);
			
		} catch (Exception e) { 
			if(e instanceof FileUploadBase.FileSizeLimitExceededException) {
				request.setAttribute("msg", "您上传的文件超出了15KB");
				request.getRequestDispatcher("/news/add.jsp")
						.forward(request, response);
			}
			throw new RuntimeException(e);
		}
	}
}
